﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Web.UI;

namespace Carbon.Web.Forms.jQueryForms
{
    public class EnvironmentControl : Control, IScriptControl
    {
		#region Classes (2)
		private class DelegateScriptDescriptor : ScriptDescriptor
        {
			#region Fields (1)
			private String m_Script = default(String);
			#endregion

			#region Properties (1)
			public String Script
            {
                get
                {
                    return m_Script;
                }
            }
			#endregion

			#region Constructors (1)
			public DelegateScriptDescriptor(string script)
                : base()
            {
                if (script == null) throw new ArgumentNullException("script");

                this.m_Script = script;
            }
			#endregion

			#region Methods (1)

			protected override string GetScript()
            {
                return Script;
            }

			#endregion
        }

		private class EnvironmentControlScriptDescriptor : ScriptDescriptor
        {
			#region Methods (1)

			protected override string GetScript()
            {
                return "Carbon_Web_Forms_jQueryForms_Resources_RegisterResources();";
            }

			#endregion
        }
		#endregion

		#region Fields (3)
		private bool m_RegisterFancybox = true;
		private bool m_RegisterJQuery = true;
		private bool m_RegisterJQueryUi = true;
		#endregion

		#region Events (2)
		public event EventHandler<ScriptDescriptorsRegisteredEventArgs> ScriptDescriptorsRegistered;

		public event EventHandler<ScriptsRegisteredEventArgs> ScriptReferencesRegistered;
		#endregion

		#region Properties (3)
		public bool RegisterFancybox
        {
            get
            {
                return m_RegisterFancybox;
            }
            set
            {
                m_RegisterFancybox = value;
            }
        }
		public bool RegisterJQuery
        {
            get
            {
                return m_RegisterJQuery;
            }
            set
            {
                m_RegisterJQuery = value;
            }
        }
		public bool RegisterJQueryUi
        {
            get
            {
                return m_RegisterJQueryUi;
            }
            set
            {
                m_RegisterJQueryUi = value;
            }
        }
		#endregion

		#region ASP Processing

		protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            ScriptManager sm = ScriptManager.GetCurrent(this.Page);
            if (sm == null) throw new NullReferenceException("sm");

            sm.RegisterScriptControl(this);
            sm.RegisterScriptDescriptors(this);


            InternalUtility.EnsureCssInclude(this.Page, typeof(Control), "jQueryFormsCss", jQueryFormsConfiguration.ServerRelativeBaseCssUrl);

            if (RegisterFancybox)
                InternalUtility.EnsureCssInclude(this.Page, typeof(Control), "jQueryFormsPopupCss", jQueryFormsConfiguration.ServerRelativePopupCssUrl);
            if (RegisterJQueryUi)
                InternalUtility.EnsureCssInclude(this.Page, typeof(Control), "jQueryFormsSkin", jQueryFormsConfiguration.ServerRelativeSkinCssUrl);
        }

		public override void RenderControl(HtmlTextWriter writer)
        {
            base.RenderControl(writer);

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Type.registerNamespace('Carbon.Web.Forms.jQueryForms');");
            sb.AppendFormat(@"(function($) {{
                var Configuration = {{ ""FilesPath"" : ""{0}"" }};
                Carbon.Web.Forms.jQueryForms.Configuration = Configuration;
                }})(jQuery);
            ", InternalUtility.EncodeJavascriptString(Configuration.Instance.FilesPath));

            writer.Write("<script type=\"text/javascript\">{0}</script>", sb.ToString());
        }

		#endregion

		#region Methods (4)

		public virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            List<ScriptDescriptor> descriptors = new List<ScriptDescriptor>() { new EnvironmentControlScriptDescriptor() };

            ScriptDescriptorsRegisteredEventArgs args = new ScriptDescriptorsRegisteredEventArgs();
            OnScriptDescriptorsRegistered(args);

            foreach (String script in args.Scripts)
            {
                descriptors.Add(new DelegateScriptDescriptor(script));
            }

            return descriptors;
        }

		public virtual IEnumerable<ScriptReference> GetScriptReferences()
        {
            ScriptsRegisteredEventArgs args = new ScriptsRegisteredEventArgs();
            OnScriptReferencesRegistered(args);

            CultureInfo culture = CultureInfo.CurrentCulture;

            List<ScriptReference> references = new List<ScriptReference>();

            string scriptsPath = PathUtility.Join(Configuration.Instance.FilesPath, "scripts", '/');

          
            if (RegisterJQuery)
                references.Add(new ScriptReference(PathUtility.Join(scriptsPath, Constants.jQueryPath, '/')));
            if (RegisterFancybox)
                references.Add(new ScriptReference(PathUtility.Join(scriptsPath, Constants.Popup3rdPartyPath, '/')));
            
            references.Add(new ScriptReference(PathUtility.Join(scriptsPath, Constants.PopupOpenerPath, '/')));
            references.Add(new ScriptReference(PathUtility.Join(scriptsPath, Constants.CarbonPath, '/')));

            if (RegisterJQueryUi)
                references.Add(new ScriptReference(PathUtility.Join(scriptsPath, Constants.jQueryUiPath, '/')));
            references.Add(new ScriptReference(PathUtility.Join(scriptsPath, Constants.TimePickerPath, '/')));
            
            if (RegisterJQueryUi)
            {
                references.Add(new ScriptReference(PathUtility.Join(scriptsPath, "/localization/jquery-ui-datepicker/jquery.ui.datepicker-" + culture.TwoLetterISOLanguageName + ".js", '/')));
                references.Add(new ScriptReference(PathUtility.Join(scriptsPath, "/localization/jquery-ui-timepicker/jquery.ui.timepicker-" + culture.TwoLetterISOLanguageName + ".js", '/')));
            }

            references.Add(new ScriptReference(Constants.ResourcesPath + culture.LCID));

            foreach (String reference in args.References)
            {
                references.Add(new ScriptReference(reference));
            }

            return references;
        }

		public virtual void OnScriptDescriptorsRegistered(ScriptDescriptorsRegisteredEventArgs args)
        {
            if (ScriptDescriptorsRegistered != null)
                ScriptDescriptorsRegistered(this, args);
        }

		public virtual void OnScriptReferencesRegistered(ScriptsRegisteredEventArgs args)
        {
            if (ScriptReferencesRegistered != null)
                ScriptReferencesRegistered(this, args);
        }

		#endregion
    }
}